<template>
  <div>
    <span v-if="config.type === 'INFO'" style="display: inline-block">{{infoLabel}}</span>
    <el-select
      v-else
      style="width: 100%"
      v-model="data"
      v-bind='$attrs'
      v-on="$listeners"
      :multiple="config.multiple"
      :filterable="config.filterable"
      :remote="config.remote"
      :allow-create="config.allowCreate"
      :collapse-tags="config.collapseTags"
      :remote-method="remoteMethod"
      clearable>
      <el-option
        v-for="item in dataList"
        :key="item[config.keyType]"
        :label="item[labelUse]"
        :value="item[config.keyType]"
        @click.native="sendSelected(item[labelUse], item)">
        <template v-if="moreLabelList.length > 1">
          <template v-for="(label, i) in moreLabelList">
            <span :key="i + '1'">{{item[label]}}</span>
            <span :key="i + '2'" v-if="i < moreLabelList.length - 1"> - </span>
          </template>
        </template>
      </el-option>
    </el-select>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  export default {
    name: 'xklSelectCommon',
    props: {
      value: {
        required: true
      },
      config: {
        type: Object
      }
    },
    data () {
      return {
        dataList: [],
        dataForm: {
          type: 1
        },
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0
      }
    },
    watch: {
      interfaceParams (newVal, oldVal) {
        // 获取旧对象键值是否都有值
        let oldNotEmptyFlag = Object.values(JSON.parse(oldVal)).every(res => res)
        // 获取新对象键值是否都有值
        let newNotEmptyFlag = Object.values(JSON.parse(newVal)).every(res => res)
        if (newVal) {
          // 如果额外参数值变化，需要清空下拉框的value值
          if (this.data && oldNotEmptyFlag) {
            this.$emit('input', '')
          }
          // 如何额外参数值变化，且额外参数值都不为空时，才会去调用接口，否则清空当前下拉列表
          if (newNotEmptyFlag) {
            this.getDataList(this.config.link)
          } else {
            this.dataList = []
          }
        }
      }
    },
    created () {
      this.init()
    },
    methods: {
      init () {
        // 判断是否是联动下拉框
        if (!this.config.linkage) {
          if (this.config.selectType && !this.config.link) {
            // 当数据取自数据字典时，数据已被缓存，无需重新调用接口
            this.dataList = this.getDictionary(this.config.selectType,  this.config.exclude)
          } else if (this.config.dataList && this.config.dataList.length) {
            this.dataList = this.config.dataList
          } else {
            // 当数据取自其它接口
            this.config.link && this.getDataList(this.config.link)
          }
        }
      },
      getDataList (url) {
        this.dataList = []
        this.$http({
          url: this.$http.adornUrl(url),
          method: this.config.method || 'get',
          [this.config.method === 'post' ? 'data' : 'params']: this.$http[this.config.method === 'post' ? 'adornData' : 'adornParams']({
            'page': this.pageIndex,
            'limit': 999,
            ...this.config.additionalData
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            // this.totalCount = data.page.totalCount
          } else {
            this.dataList = []
            // this.totalCount = 0
          }
        })
      },
      sendSelected (label, item) {
        // 当下拉框为多选的时候，将labelList和itemList返回到config对象中
        if (this.config.multiple) {
          this.$nextTick(() => {
            this.config.labelList = this.dataList.filter(res => this.data.indexOf(res[this.config.keyType]) > -1).map(next => next[this.config.labelType]) || []
            this.config.currentItemList = this.dataList.filter(res => this.data.indexOf(res[this.config.keyType]) > -1).map(next => next) || []
            this.$emit('getSelected', this.config.labelList, this.config.currentItemList)
          })
        } else {
          // 将label和item值返回到config对象中
          this.$nextTick(() => {
            this.config.label = label
            this.config.currentItem = item
            this.$emit('getSelected', label, item)
          })
        }
      },
      remoteMethod (query) {
        if (!this.config.additionalData) { this.config.additionalData = {} }
        this.config.additionalData[this.config.remoteField] = query
        this.getDataList(this.config.link, query)
      }
    },
    computed: {
      ...mapGetters([
        'getDictionary'
      ]),
      data: {
        get () { return this.value },
        set (value) { this.$emit('input', value) }
      },
      labelUse () {
        return this.config.labelType.split(',')[0]
      },
      moreLabelList () {
        return this.config.labelType.split(',') || []
      },
      infoLabel () {
        // 用于读取下拉框的label值
        if (this.config.type === 'INFO' && this.dataList.find(res => res[this.config.keyType] === this.value)) {
          return this.dataList.find(res => res[this.config.keyType] === this.value)[this.config.labelType]
        }
        return ''
      },
      interfaceParams () {
        return this.config.additionalData && JSON.stringify(this.config.additionalData)
      }
    }
  }
</script>
<style lang="less" scoped>
</style>
